/*
* @Date: 2020/4/15
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import React from 'react';
import './index.scss';
import VerticalDivider from '@/components/VerticalDivider';
import Editor from '../Editor';
import Viewer from '../Viewer';
import Domer from '../Domer';
import HorizontalDivider from '@/components/HorizontalDivider';
import { Tabs } from 'antd';
const { TabPane } = Tabs;
import Component from '../Component';
import componentsMap from 'utils/componentsMap';
import $ from 'jquery'
import 'jquery-ui';
import ReactDOM from 'react-dom';
import NewProject from '../Modal/NewProject';
import Ele from '../../ele';
import { getUuid } from 'utils/common';
import Directory from '../Directory';
import NewComponent from '../Modal/NewComponent';
import Descriptions from '../../descriptions';
const { remote } = window.require('electron');
const file = remote.require('./server/file');
import { parsePage } from 'utils/parser';
import Attribute from '../Attribute';


export default class extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabKey: 1,
      childRender: '',
      showNewProject: false,
      dom: <React.Fragment />,
      currentComponent: '',
      currentProps: {},
      currentUid: '',
    };
    this.currentDom = null;
    this.page = {

    }
  }

  onSortableUpdate = (e,t) => {
    $(t.item[0]).empty();
    const div = document.createElement('div');
    const drag = document.createElement('span');
    $(drag).html('X');
    $(drag).addClass('drag');
    $(div).addClass('view-item-box');
    $(t.item[0]).append(div);
    $(t.item[0]).append(drag);
    const componentId = getUuid();
    const componentName = $(t.item[0]).attr('data-component');
    $(div).attr('id', componentId);
    $(div).attr('data-component', componentName);
    const component = componentsMap[$(t.item[0]).attr('data-component')];
    const props = {};
    if (Descriptions[componentName]) {
      let children;
      console.log('Descriptions[componentName]', Descriptions[componentName].display, Descriptions[componentName])
      $(div).css('display', Descriptions[componentName].display);
      $(t.item[0]).css('display', Descriptions[componentName].display);
      for (let i = 0; i < Descriptions[componentName].props; i++) {
        const prop = Descriptions[componentName].props[i];
        props[prop.key] = prop.defaultValue;
      }
      if (Descriptions[componentName].childParamer) {
        Descriptions[componentName]
          .childParamer()
          .then((params) => {
            if (Descriptions[componentName].childRender) {
              children = Descriptions[componentName].childRender(params, this.page);
              props.children = children
            }
            const virtualDom = React.createElement(component, props);
            this.page[componentId] = virtualDom;
            ReactDOM.render(virtualDom, div);
            $('.sortable' ).sortable({
              connectWidth:'.sortable',
              handle:'.drag',
              update: this.onSortableUpdate,
            });
            this.setState({
              dom: <React.Fragment>{ parsePage(document.getElementsByClassName('view-box')[0], this.page) }</React.Fragment>
            });
          });
      } else {
        const virtualDom = React.createElement(component, props);
        this.page[componentId] = virtualDom;
        ReactDOM.render(virtualDom, div);
        $('.sortable' ).sortable({
          connectWidth:'.sortable',
          handle:'.drag',
          update: this.onSortableUpdate,
        });
        this.setState({
          dom: <React.Fragment>{ parsePage(document.getElementsByClassName('view-box')[0], this.page) }</React.Fragment>
        });
      }
    } else {
      const virtualDom = React.createElement(component, props);
      this.page[componentId] = virtualDom;
      ReactDOM.render(virtualDom, div);
      $('.sortable' ).sortable({
        connectWidth:'.sortable',
        handle:'.drag',
        update: this.onSortableUpdate,
      });
      this.setState({
        dom: <React.Fragment>{ parsePage(document.getElementsByClassName('view-box')[0], this.page) }</React.Fragment>
      });
    }
  }

  componentDidMount() {
    $(document).on('click', '.view-item-box', (e) => {
      const div = e.currentTarget;
      const componentName = $(div).attr('data-component');
      const uid = $(div).attr('id');
      this.currentDom = div;
      const component = this.page[uid];
      const { props } = component;
      this.setState({
        currentUid: uid,
        currentProps: {
          ...props,
          children: undefined,
        },
        currentComponent: componentName,
      });

    })
    XUE.win.addEventListener('newproject', 'context-menu', () => {
      this.setState({
        showNewProject: true
      });
    });
    XUE.win.addEventListener('project-update', 'user', () => {
      this.setState({
        project: Ele.getProject()
      });
    });
    $('.sortable' ).sortable({
      connectWidth:'.sortable',
      handle:'.drag',
      update: this.onSortableUpdate,
    });
    $('.component-box .draggable').draggable({
      connectToSortable: '.sortable',
      helper: 'clone',
      handle:'.drag',
    });
  }

  onNewProject = (dirPath) => {
    file.openDirectory(dirPath)
      .then(res => {
        Ele.newProject(dirPath);
        this.setState({
          project: Ele.getProject(),
          showNewProject: false
        });
      }).catch(err => {
        console.log('err', err);
    });
  }

  onPropsChange = (option) => {
    const { key, value, uid, component } = option;
    const virtualDom = this.page[uid];
    const { props } = virtualDom;
    const targetDom = React.createElement(componentsMap[component], {
      ...props,
      [key]: value,
    });
    this.page[uid] = targetDom;
    ReactDOM.render(targetDom, this.currentDom);
    this.setState({
      currentUid: uid,
      currentProps: {
        ...props,
        [key]: value,
        children: undefined,
      },
      currentComponent: component,
      dom: <React.Fragment>{ parsePage(document.getElementsByClassName('view-box')[0], this.page) }</React.Fragment>
    });
  }

  // onNewPageSuccess = (name) => {
  //   this.setState({
  //     project: Ele.getProject()
  //   });
  // }

  render() {
    const {
      tabKey, childRender, showNewProject, project, dom,
      currentComponent, currentProps, currentUid,
    } = this.state;
    return (
      <React.Fragment>
        <div className="home-webview">
          <div className="home-file-and-quotation">
            {/*<Directory project={project} />*/}
            <Component />
          </div>
          <VerticalDivider style={{flex: '0 0 10px'}} />
          <div className="home-quotation-chart">
            <div className="home-quotation-chart-view">
              <Viewer childRender={childRender} />
            </div>
            <HorizontalDivider />
            <div className="home-quotation-chart-editor">
              <Tabs defaultActiveKey={tabKey} >
                <TabPane tab="视图" key={1}>
                  <Domer dom={dom} />
                </TabPane>
                <TabPane tab="代码" key={2}>
                  <Editor />
                </TabPane>
              </Tabs>
            </div>
          </div>
          <VerticalDivider style={{flex: '0 0 10px'}} />
          <div className="home-editor">
            <Attribute
              uid={currentUid}
              propsValue={currentProps}
              component={currentComponent}
              onPropsChange={this.onPropsChange}
            />
          </div>
        </div>
        <NewProject
          visible={showNewProject}
          onCancel={() => this.setState({showNewProject: false})}
          onOk={this.onNewProject}
        />
      </React.Fragment>

    );
  }
}
